﻿using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.FileProviders;
using SBlogCore.Common.AutofacExtend;
using SBlogCore.Common.LogExtend;
using SBlogCore.Common.MiddlewareExtend;
using SBlogCore.Common.SwaggerExtend;
using System.Reflection;
using Microsoft.AspNetCore.Hosting;
using SBlogCore.Common.App;
using SBlogCore.Common.App.Manager;
using SBlogCore.Common.Attributes;
using SBlogCore.Common.DatabaseAccessor.Extend;
using SBlogCore.EventBus.CrossProcessEventBus;

namespace SBlogCore.Program
{
    [SkipScan]
    public static class AppProgram
    {
        public static async  Task RunSBlogAsync(this WebApplicationBuilder builder)
        {
            #region 日志配置
            builder.AddSerilogSetUp();
            #endregion
            #region 服务注册
            builder.Services.AddSBlogServices();
            #endregion
            #region 注册Autofac
            builder.Host.AutofacRegister();
            builder.WebHost.UseUrls("http://*:5258");
            #endregion
            #region 管道中间件
            WebApplication app = builder.Build();
            AppBase.SetInstance(app);
            //Environment.CurrentDirectory  获取当前环境的物理路径
            app.UseSwaggerMildd(() => Assembly.Load("SBlogCore.Api").GetManifestResourceStream("SBlogCore.Api.index.html")!);
            var uploadFilePath = AppSetting.ReadAppSettings("UploadFile:UploadFilePath");
            if (!string.IsNullOrWhiteSpace(uploadFilePath))
            {
                var options = new StaticFileOptions
                {
                    //D:\.NET\SBlogCore\SBlogCore.Api\SBlogCore.Api\upload 物理路径
                    FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), uploadFilePath)),
                    RequestPath = $"/{uploadFilePath}"
                };
                app.UseStaticFiles(options);
            }
            else
            {
                app.UseStaticFiles();
            }
            //app.UseHttpsRedirection();
            //路由
            app.UseRouting();
            //JWT认证
            app.UseAuthentication();
            //授权中间件
            app.UseAuthorization();
            //服务器响应缓存
            //app.UseResponseCaching();
            app.MapControllers();
            app.UseEventBus();
            //添加自定义中间件
            app.UseMiddleware<MigrateDataBaseMiddleware>();
            //迁移数据库
            await app.UseMigrateDataBaseAsync();
            await app.RunAsync();
            #endregion
        }
    }
}
